package com.example.lesson2;

import java.util.concurrent.TimeUnit;

import com.example.pages.*;
import org.junit.*;
import static org.junit.Assert.*;

import org.openqa.selenium.*;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.PageFactory;
import ru.esteru.selenium.factory.WebDriverFactory;

public class TC005FilmsList {
    private static WebDriver driver;
    private static String baseUrl;
    private static StringBuffer verificationErrors = new StringBuffer();
    private LoginPage loginPage;
    private FilmsPage filmsPage;
    private FilmPage filmPage;

    @Before
    public void setUp() throws Exception {
        driver = WebDriverFactory.getDriver(DesiredCapabilities.firefox());
        baseUrl = "http://localhost/";
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }

    @Test
    public void FilmsList() throws Exception {
        goToMainPage();
        loginAs("admin", "admin");
        goToFilmsPage();
        selectFilm("Happy");
        logout();
    }

    private void selectFilm(String filmName) {
        for (int i=0; i<filmsPage.linksToFilms.size();i++){
            WebElement divTitle=filmsPage.linksToFilms.get(i).findElement(By.xpath(".//div[@class='title']"));
            if (divTitle.getText().equals(filmName)){
                filmsPage.linksToFilms.get(i).click();
                assertTrue(filmPage.filmTitle.getText().contains(filmName));
                return;
            }
        }
        fail("film is not found: '"+filmName+"'");
    }

    private void goToFilmsPage() {
        filmsPage.menuHomeLink.click();
    }

    private void logout() {
        filmsPage.menuLogoutLink.click();
        driver.switchTo().alert().accept();
//        driver.quit();
    }

    private void loginAs(String username, String password) {
        loginPage.userNameField.clear();
        loginPage.userNameField.sendKeys(username);
        loginPage.passwordField.clear();
        loginPage.passwordField.sendKeys(password);
        loginPage.loginButton.click();
    }

    private void goToMainPage() {
        driver.get(baseUrl + "/php4dvd/");
        loginPage = PageFactory.initElements(driver, LoginPage.class);
        filmsPage = PageFactory.initElements(driver, FilmsPage.class);
        filmPage = PageFactory.initElements(driver, FilmPage.class);

    }

    @After
    public void tearDown() throws Exception {
        String verificationErrorString = verificationErrors.toString();
        if (!"".equals(verificationErrorString)) {
            fail(verificationErrorString);
        }
    }

}
